MOOC Utils

Utils like auto assignment solver extension and course notice announcment notification for MOOC courses

Screenshot capture handler

Introduction#

Captures full-page screenshots for visual context in Gemini prompts. Stitching long pages, data URL handling, and failure modes are the main topics.

System architecture#

The screenshot capture system follows a layered architecture pattern :

Components stay loosely coupled with a straightforward data flow. The system handles cross-browser compatibility through platform adapters and provides reliable error handling mechanisms.

Screenshot generation process#

The screenshot generation process uses a detailed multi-step approach built to handle long web pages efficiently:

The process begins by analyzing the page dimensions to determine the number of viewport captures needed. The system calculates the optimal number of screenshots based on the page height and viewport dimensions, with intelligent limiting to prevent excessive API usage.

Image encoding and response formatting#

The screenshot capture system implements a standardized encoding and response format that keeps compatibility across different browsers and platforms:

Data URL processing#

The system captures screenshots in JPEG format and processes them through a structured data URL parsing mechanism:

Property Type Description
mimeType string MIME type extracted from data URL (e.g., “image/jpeg”)
base64 string Base64-encoded image data without data URL prefix
scrollY number Vertical scroll position for this screenshot
index number Sequential index of this screenshot in the sequence
total number Total number of screenshots captured

Response structure#

The handler returns a detailed response object containing all captured screenshots with metadata:

The response shape matches what Gemini expects: image bytes plus enough metadata to keep context.

Supported formats and quality settings#

Screenshot capture currently uses one image format with fixed quality settings:

Image format specifications#

Parameter Value Description
Format jpeg JPEG compression format
Quality 60 Compression quality percentage (1-100 scale)
MIME Type image/jpeg Standard MIME type identifier

Format selection rationale#

The JPEG format was chosen for several strategic reasons:

  1. Compression Efficiency: Reduces file size significantly and keeps acceptable quality
  2. Universal Support: Ensures compatibility across all supported browsers
  3. Memory Efficiency: Lower memory footprint compared to PNG or WebP formats
  4. AI Optimization: Balanced quality-to-size ratio suitable for AI processing

Quality impact analysis#

The selected quality setting of 60 provides an optimal balance between:

  • File Size: Reduced bandwidth and storage requirements
  • Visual Clarity: Sufficient detail for AI recognition tasks
  • Processing Speed: Faster transmission and processing times

Size limitations#

Size limits stack so captures stay within browser and API caps:

Per-Screenshot limits#

Metric Limit Purpose
Base64 Length No explicit limit System relies on browser API constraints
Viewport Count Maximum 8 screenshots Prevents API throttling and memory issues
Individual Image Size Browser-dependent Limited by available memory and API constraints

Intelligent limiting mechanism#

The system calculates the required number of screenshots and applies intelligent limiting:

Memory management#

The system implements careful memory management to prevent browser crashes:

  • Sequential Processing: Screenshots are captured one at a time
  • Automatic Cleanup: Previous scroll positions are restored
  • Graceful Degradation: Partial failures don’t halt the entire process

Integration with UI panel#

The screenshot capture handler integrates smoothly with the side panel UI through a well-defined communication protocol:

UI preview integration#

Communication protocol#

The integration uses the established message-based communication system:

Message Type Direction Purpose
CAPTURE_FULL_PAGE UI → Background Request screenshot capture
Response Background → UI Return screenshot data
GEMINI_DEBUG Background → Content Debug information relay

UI state management#

The side panel maintains synchronized state during screenshot operations:

  • Loading States: Visual feedback during capture
  • Error Handling: Graceful degradation on failures
  • Preview Updates: Real-time thumbnail rendering

Error handling#

The screenshot capture system implements detailed error handling strategies so operation stays reliable:

Error categories and handling#

Error Type Detection Method Handling Strategy User Impact
Permission Denied SecurityError Skip screenshots, continue processing Reduced AI accuracy warning
API Limit Exceeded NS_ERROR_FAILURE Retry with reduced quality Automatic quality adjustment
Tab Unavailable Invalid tab ID Fallback to HTML extraction Complete processing still possible
Memory Issues OutOfMemoryError Limit screenshot count Reduced visual context
Network Failure Connection error Retry with exponential backoff Temporary unavailability

Reliability features#

The system incorporates several built-in safeguards:

  1. Graceful Degradation: Screenshots are optional for AI processing
  2. Partial Success: Individual screenshot failures don’t halt the entire process
  3. Resource Management: Automatic cleanup of temporary resources
  4. Logging: Detailed error tracking for debugging

Error recovery mechanisms#

Usage examples#

Basic screenshot capture#

The most common usage scenario involves capturing full-page screenshots for assignment analysis:

javascript
// Example: Capturing screenshots for an NPTEL assignment
const screenshotResult = await sendMessageWithRetry(
 runtime,
 {
 type: MESSAGE_TYPES.CAPTURE_FULL_PAGE,
 tabId: targetTabId,
 windowId: targetWindowId,
 },
 { maxRetries: 3, baseDelay: 200 }
);

// Process the returned screenshots
const screenshots = screenshotResult?.screenshots || [];
console.log(`Captured ${screenshots.length} screenshots`);

Integration with AI processing#

Screenshots are smoothly integrated with the Gemini AI service:

javascript
// Example: Using screenshots with AI extraction
const extraction = await gemini.extract(
 apiKey,
 pageData.html,
 pageInfo,
 pageData.images || [],
 screenshots, // ← Screenshots passed here
 model,
 reasoningLevel
);

Error handling implementation#

javascript
// Example: screenshot capture with error handling
let screenshots = [];
try {
 const screenshotResult = await this.captureFullPageScreenshots(
 targetTabId,
 pageData.windowId
 );
 screenshots = screenshotResult?.screenshots || [];
} catch (ssError) {
 logger.log(`Screenshot capture failed: ${ssError.message}`);
 // Continue without screenshots
}

Performance considerations#

Performance notes for common capture cases:

Memory optimization#

  • Streaming Capture: Screenshots are processed individually to minimize memory usage
  • Automatic Cleanup: Previous scroll positions are restored immediately
  • Resource Limits: Built-in caps prevent excessive resource consumption

Network efficiency#

  • JPEG Compression: Optimized compression reduces bandwidth usage
  • Quality Tuning: Balanced quality vs. size ratio
  • Batch Processing: Intelligent batching prevents API throttling

Browser compatibility#

The system adapts to different browser capabilities:

  • Chrome: Full feature support with advanced APIs
  • Firefox: Graceful degradation with alternative approaches
  • Cross-Browser: Consistent behavior across platforms

Troubleshooting guide#

Common issues and solutions#

Issue Symptoms Solution
Permission Denied Error: “Permission denied” Request screenshot permissions in extension settings
No Screenshots Returned Empty screenshots array Check page scrollability and content
Slow Capture Performance Long delays in capture Reduce page complexity or disable animations
Quality Issues Low-resolution screenshots Adjust browser zoom level or page scaling
Memory Errors Browser crashes during capture Close other tabs and reduce screenshot count

Debugging steps#

  1. Enable Debug Logging: Check browser console for detailed error messages
  2. Test Permissions: Verify extension has screenshot permissions
  3. Validate Page State: Ensure target page is fully loaded
  4. Monitor Resources: Watch for memory usage spikes
  5. Check Network: Verify internet connectivity for AI processing

Performance monitoring#

The system provides detailed logging for troubleshooting:

  • Operation Timing: Capture duration and processing times
  • Error Tracking: Detailed error messages and stack traces
  • Resource usage. Memory and CPU use
  • Success Rates: Capture success statistics over time

Conclusion#

Long pages are scrolled and stitched. Prefer screenshots when text extraction alone loses diagrams or equations.